package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcMenuMapper xcMenuMapper;
    @Autowired
    ApplicationContext applicationContext;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求格式不符合需求{}",s);
            throw new RuntimeException("认证请求格式不符合需求");
        }
        String authType = authParamsDto.getAuthType();
        String bean=authType+"_authservice";
        AuthService authService =applicationContext.getBean(bean,AuthService.class);
        //获取到用户名
        XcUserExt xcUser = authService.execute(authParamsDto);
//        //如果数据库里查询结果为空则返回为空
//        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername,username));
//        if (xcUser==null){
//            return null;
//        }
//        //获取密码交给SpringSecurity框架验证
//        String password = xcUser.getPassword();
        UserDetails userDetails = getUserPrincipal(xcUser);
        return userDetails;
    }

    private UserDetails getUserPrincipal(XcUserExt xcUser) {
        String password=xcUser.getPassword();
        String[] authorities= {"test"};
        //为了安全不在令牌中放密码
        xcUser.setPassword(null);
        //查看用户所属角色所拥有的权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        authorities = xcMenus.stream().map(XcMenu::getCode).toArray(String[]::new);
        String jsonString = JSON.toJSONString(xcUser);
        UserDetails userDetails = User.withUsername(jsonString).password(password).authorities(authorities).build();
        return userDetails;
    }
}
